package com.segersten.othello.service.rest;

import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

import com.segersten.othello.service.akka.Auth;

public enum AuthenticateService {

	INSTANCE;

	private Set<Auth> auths;
	private AtomicLong counter = new AtomicLong();

	private AuthenticateService() {
		auths = init("config/auth.conf");
	}

	/**
	 * Class is package protected to allow a unit test
	 */
	Set<Auth> init(String filename) {
	    Set<Auth> tempAuths = new HashSet<Auth>();
	    Properties p = new Properties();
	    try {
            p.load(new FileInputStream(filename));
            for(Entry<Object,Object> entry : p.entrySet()) {
                tempAuths.add(new Auth(entry.getKey().toString(), entry.getValue().toString()));
            }
            System.out.println("Successfully loaded " + tempAuths.size() + " users");
        } catch (Exception e) {
            tempAuths = new HashSet<Auth>();
            e.printStackTrace();
            System.out.println("Failed to load " + filename);
        } 
		auths = tempAuths;
		return tempAuths;
	}

	public boolean isOK(Auth auth) {
	    System.out.println("Auth " + auth);
	    System.out.println("Auths " + auths);
		return auths.contains(auth);
	}

    public Auth generateToken(String domain, String nickname)
    {
        return new Auth("p"+domain, nickname+"secret_token"+counter.incrementAndGet());
    }

}
